<template>
  <div class="my-posts">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>我的帖子</h1>
        <p>管理您发布的所有帖子</p>
      </div>

      <!-- 统计信息 -->
      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ totalPosts }}</div>
                <div class="stat-label">总帖子数</div>
              </div>
              <i class="el-icon-document stat-icon"></i>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ totalViews }}</div>
                <div class="stat-label">总浏览量</div>
              </div>
              <i class="el-icon-view stat-icon"></i>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ totalReplies }}</div>
                <div class="stat-label">总回复数</div>
              </div>
              <i class="el-icon-chat-dot-round stat-icon"></i>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ totalFavorites }}</div>
                <div class="stat-label">总收藏数</div>
              </div>
              <i class="el-icon-star-off stat-icon"></i>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 筛选和操作区域 -->
      <div class="filter-section">
        <el-row :gutter="20" type="flex" justify="space-between" align="middle">
          <el-col :span="12">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索我的帖子..."
              prefix-icon="el-icon-search"
              @input="filterPosts"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="selectedCategory" placeholder="筛选分类" @change="filterPosts" clearable>
              <el-option label="全部分类" value=""></el-option>
              <el-option label="养护经验" value="care"></el-option>
              <el-option label="领养心得" value="adoption"></el-option>
              <el-option label="健康咨询" value="health"></el-option>
              <el-option label="训练技巧" value="training"></el-option>
              <el-option label="其他交流" value="other"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="goToCreatePost" icon="el-icon-plus">
              发布新帖
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 帖子列表 -->
      <div class="posts-section">
        <el-card v-if="loading" class="loading-card">
          <div class="loading-content">
            <i class="el-icon-loading"></i>
            <span>加载中...</span>
          </div>
        </el-card>

        <div v-else-if="filteredPosts.length === 0" class="empty-state">
          <i class="el-icon-document"></i>
          <p>{{ searchKeyword || selectedCategory ? '没有找到匹配的帖子' : '您还没有发布任何帖子' }}</p>
          <el-button type="primary" @click="goToCreatePost">发布第一个帖子</el-button>
        </div>

        <div v-else class="posts-list">
          <el-card 
            v-for="post in paginatedPosts" 
            :key="post.id" 
            class="post-card"
          >
            <div class="post-header">
              <div class="post-category">
                <el-tag :type="getCategoryType(post.category)" size="small">
                  {{ getCategoryName(post.category) }}
                </el-tag>
                <el-tag v-if="post.status === 'draft'" type="info" size="small">草稿</el-tag>
              </div>
              <div class="post-actions">
                <el-dropdown @command="(command) => handleCommand(command, post)">
                  <el-button type="text" icon="el-icon-more">
                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="`view-${post.id}`">查看详情</el-dropdown-item>
                    <el-dropdown-item :command="`edit-${post.id}`">编辑帖子</el-dropdown-item>
                    <el-dropdown-item :command="`stats-${post.id}`">查看统计</el-dropdown-item>
                    <el-dropdown-item :command="`delete-${post.id}`" divided>删除帖子</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
            
            <h3 class="post-title" @click="viewPost(post.id)">{{ post.title }}</h3>
            <p class="post-summary">{{ post.summary }}</p>
            
            <div class="post-meta">
              <div class="post-stats">
                <span class="stat-item">
                  <i class="el-icon-view"></i>
                  {{ post.viewCount || 0 }}
                </span>
                <span class="stat-item">
                  <i class="el-icon-chat-dot-round"></i>
                  {{ post.replyCount || 0 }}
                </span>
                <span class="stat-item">
                  <i class="el-icon-star-off"></i>
                  {{ post.favoriteCount || 0 }}
                </span>
              </div>
              <div class="post-time">
                <span>发布于 {{ formatTime(post.createdAt) }}</span>
                <span v-if="post.updatedAt && post.updatedAt !== post.createdAt">
                  · 更新于 {{ formatTime(post.updatedAt) }}
                </span>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 分页 -->
        <div v-if="filteredPosts.length > pageSize" class="pagination-wrapper">
          <el-pagination
            @current-change="handlePageChange"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="filteredPosts.length"
            layout="prev, pager, next, jumper"
          >
          </el-pagination>
        </div>
      </div>

      <!-- 帖子统计对话框 -->
      <el-dialog
        title="帖子统计"
        :visible.sync="statsDialogVisible"
        width="600px"
      >
        <div v-if="selectedPostStats" class="stats-dialog">
          <h3>{{ selectedPostStats.title }}</h3>
          <el-row :gutter="20" class="stats-row">
            <el-col :span="6">
              <div class="stat-item-large">
                <div class="stat-number">{{ selectedPostStats.viewCount || 0 }}</div>
                <div class="stat-label">浏览量</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item-large">
                <div class="stat-number">{{ selectedPostStats.replyCount || 0 }}</div>
                <div class="stat-label">回复数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item-large">
                <div class="stat-number">{{ selectedPostStats.favoriteCount || 0 }}</div>
                <div class="stat-label">收藏数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item-large">
                <div class="stat-number">{{ selectedPostStats.shareCount || 0 }}</div>
                <div class="stat-label">分享数</div>
              </div>
            </el-col>
          </el-row>
          <div class="stats-chart">
            <p>发布时间：{{ formatTime(selectedPostStats.createdAt) }}</p>
            <p v-if="selectedPostStats.updatedAt && selectedPostStats.updatedAt !== selectedPostStats.createdAt">
              最后更新：{{ formatTime(selectedPostStats.updatedAt) }}
            </p>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MyPosts',
  data() {
    return {
      loading: true,
      searchKeyword: '',
      selectedCategory: '',
      currentPage: 1,
      pageSize: 10,
      statsDialogVisible: false,
      selectedPostStats: null,
      posts: [
        // 模拟数据
        {
          id: 1,
          title: '新手养猫必看：猫咪日常护理指南',
          summary: '分享一些养猫新手必须知道的日常护理知识，包括喂食、清洁、健康检查等方面的经验...',
          category: 'care',
          status: 'published',
          viewCount: 156,
          replyCount: 23,
          favoriteCount: 45,
          shareCount: 12,
          createdAt: new Date('2024-01-15 10:30:00'),
          updatedAt: new Date('2024-01-15 10:30:00')
        },
        {
          id: 2,
          title: '狗狗训练心得分享',
          summary: '经过几个月的训练，我家狗狗终于学会了基本指令，分享一些训练经验...',
          category: 'training',
          status: 'draft',
          viewCount: 0,
          replyCount: 0,
          favoriteCount: 0,
          shareCount: 0,
          createdAt: new Date('2024-01-16 14:20:00'),
          updatedAt: new Date('2024-01-16 15:30:00')
        },
        {
          id: 3,
          title: '宠物健康检查的重要性',
          summary: '定期的健康检查对宠物来说非常重要，可以及早发现和预防疾病...',
          category: 'health',
          status: 'published',
          viewCount: 89,
          replyCount: 12,
          favoriteCount: 28,
          shareCount: 5,
          createdAt: new Date('2024-01-14 09:15:00'),
          updatedAt: new Date('2024-01-14 09:15:00')
        }
      ]
    }
  },
  computed: {
    filteredPosts() {
      let filtered = this.posts

      // 分类筛选
      if (this.selectedCategory) {
        filtered = filtered.filter(post => post.category === this.selectedCategory)
      }

      // 搜索筛选
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(post => 
          post.title.toLowerCase().includes(keyword) ||
          post.summary.toLowerCase().includes(keyword)
        )
      }

      return filtered
    },
    paginatedPosts() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredPosts.slice(start, end)
    },
    totalPosts() {
      return this.posts.length
    },
    totalViews() {
      return this.posts.reduce((sum, post) => sum + (post.viewCount || 0), 0)
    },
    totalReplies() {
      return this.posts.reduce((sum, post) => sum + (post.replyCount || 0), 0)
    },
    totalFavorites() {
      return this.posts.reduce((sum, post) => sum + (post.favoriteCount || 0), 0)
    }
  },
  methods: {
    async loadPosts() {
      this.loading = true
      try {
        // 这里应该调用API获取用户的帖子
        // const response = await this.$api.forum.getMyPosts()
        // this.posts = response.data
        
        // 模拟加载延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
      } catch (error) {
        this.$message.error('加载帖子失败')
        console.error('加载帖子失败:', error)
      } finally {
        this.loading = false
      }
    },

    filterPosts() {
      this.currentPage = 1
    },

    handlePageChange(page) {
      this.currentPage = page
    },

    handleCommand(command, post) {
      const [action, postId] = command.split('-')
      
      switch (action) {
        case 'view':
          this.viewPost(post.id)
          break
        case 'edit':
          this.editPost(post.id)
          break
        case 'stats':
          this.showStats(post)
          break
        case 'delete':
          this.deletePost(post)
          break
      }
    },

    viewPost(postId) {
      this.$router.push(`/forum/post/${postId}`)
    },

    editPost(postId) {
      this.$router.push(`/forum/edit/${postId}`)
    },

    showStats(post) {
      this.selectedPostStats = post
      this.statsDialogVisible = true
    },

    async deletePost(post) {
      try {
        await this.$confirm(`确定要删除帖子"${post.title}"吗？`, '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 这里应该调用API删除帖子
        // await this.$api.forum.deletePost(post.id)
        
        const index = this.posts.findIndex(p => p.id === post.id)
        if (index > -1) {
          this.posts.splice(index, 1)
        }
        
        this.$message.success('帖子已删除')
        
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
          console.error('删除帖子失败:', error)
        }
      }
    },

    goToCreatePost() {
      this.$router.push('/forum/create')
    },

    getCategoryName(category) {
      const categoryMap = {
        care: '养护经验',
        adoption: '领养心得',
        health: '健康咨询',
        training: '训练技巧',
        other: '其他交流'
      }
      return categoryMap[category] || '未知分类'
    },

    getCategoryType(category) {
      const typeMap = {
        care: 'success',
        adoption: 'primary',
        health: 'warning',
        training: 'info',
        other: ''
      }
      return typeMap[category] || ''
    },

    formatTime(date) {
      if (!date) return ''
      const now = new Date()
      const diff = now - new Date(date)
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (days === 0) {
        const hours = Math.floor(diff / (1000 * 60 * 60))
        if (hours === 0) {
          const minutes = Math.floor(diff / (1000 * 60))
          return minutes <= 0 ? '刚刚' : `${minutes}分钟前`
        }
        return `${hours}小时前`
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return new Date(date).toLocaleDateString()
      }
    }
  },

  mounted() {
    this.loadPosts()
  }
}
</script>

<style scoped>
.my-posts {
  background: #f8f9fa;
  min-height: 100vh;
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.stats-section {
  margin-bottom: 30px;
}

.stat-card {
  text-align: center;
  position: relative;
  overflow: hidden;
}

.stat-card .el-card__body {
  padding: 20px;
}

.stat-content {
  position: relative;
  z-index: 2;
}

.stat-number {
  font-size: 2em;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-label {
  color: #7f8c8d;
  font-size: 14px;
}

.stat-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 3em;
  color: #e8f4fd;
  z-index: 1;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.empty-state i {
  font-size: 64px;
  color: #ddd;
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 16px;
  color: #909399;
  margin-bottom: 20px;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.post-card {
  transition: all 0.3s ease;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.post-category .el-tag {
  margin-right: 8px;
}

.post-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
  line-height: 1.4;
  cursor: pointer;
  transition: color 0.3s ease;
}

.post-title:hover {
  color: #409eff;
}

.post-summary {
  color: #7f8c8d;
  line-height: 1.6;
  margin: 0 0 16px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #909399;
}

.post-stats {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-item i {
  font-size: 14px;
}

.post-time {
  color: #c0c4cc;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.stats-dialog h3 {
  margin-bottom: 20px;
  color: #2c3e50;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-item-large {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-item-large .stat-number {
  font-size: 2em;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-item-large .stat-label {
  color: #7f8c8d;
  font-size: 14px;
}

.stats-chart {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stats-chart p {
  margin: 8px 0;
  color: #606266;
}

</style>